package com.hkunderground.blog;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.hkunderground.blog.helper.ConstantHelper;

public class AddEntryServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

   private static final Logger log = Logger.getLogger(AddEntryServlet.class.getName());

   public void doGet(HttpServletRequest req, HttpServletResponse resp)  throws IOException
   { 
	   this.doPost(req, resp);
   }//doGet
   
   
	 public void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws IOException 
     {
		  UserService userService = UserServiceFactory.getUserService();
	      User user = userService.getCurrentUser();

	        if (user != null) 
	        {
	            resp.setContentType("text/plain");
	            resp.getWriter().println("hkunderground, blog -> " + user.getNickname());
	            
	            
	            //the kind of key, the name of key
	            Key loBlogKey = KeyFactory.createKey(ConstantHelper.KEY_KIND_BLOG, ConstantHelper.KEY_NAME_BLOG_HKUG);
	            String lsContent = req.getParameter(ConstantHelper.PARA_CONTENT);
	            Date loDate = new Date();
	            Entity loBlogEntity = new Entity(ConstantHelper.ENTITY_BLOG, loBlogKey);
	            loBlogEntity.setProperty(ConstantHelper.E_BLOG_USER, user);
	            loBlogEntity.setProperty(ConstantHelper.E_BLOG_DATE, loDate);
	            loBlogEntity.setProperty(ConstantHelper.E_BLOG_CONTENT, lsContent);

	            DatastoreService loDatastore = DatastoreServiceFactory.getDatastoreService();
	          //save
	            loDatastore.put(loBlogEntity);

	            resp.sendRedirect("/viewEntry.jsp");
	            
	            
	        } else {
	            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
	        }//if user 1
	        
     }//doGet
	
}//BlogServlet
